<template>
  <div class="app-container">
    <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
    <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
      <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
    </el-table>
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { formatExcelDate } from '@/utils/index'
import { postImport } from '@/api/employees'
export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    // 批量导入请求
    async lodeImport(data) {
      try {
        const res = await postImport(data)
        console.log('postImport', res)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 新增成功跳转页面
        this.$router.back()
      } catch (err) {
        console.log('postImport', err)
      }
    },
    // 数据转换
    zhZhuanEn(data) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      return data.map(zhkey => {
        const obj = {}

        Object.keys(zhkey).forEach(item => {
          const enkey = mapInfo[item]
          // zhkey[item] 是data的值 [44505,小张,9002,13800000252,44892,总裁办]
          if (enkey === 'correctionTime' || enkey === 'timeOfEntry') {
            obj[enkey] = new Date(formatExcelDate(zhkey[item]))
          } else {
            obj[enkey] = zhkey[item]
          }
        })
        return obj
      })
    },
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    handleSuccess({ results, header }) {
      this.tableData = results
      this.tableHeader = header
      // console.log(results, header)
      const data = this.zhZhuanEn(results)
      this.lodeImport(data)
    }
  }
}
</script>
